package com.gopay.bis.web.controller.ebank;

import java.math.BigDecimal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.gopay.bis.domain.order.OrderInfo;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.unionpay.ebank.UnionPayMessage;
import com.gopay.common.util.MoneyUtil;
/**
 * 银联前台银行回应
 * 
 * @UnionPayFrontRes.java
 * @author LILILI
 */
@Controller
@Scope("prototype")
public class UnionPayFrontRes extends BankResBase {
private static Log logger = LogFactory.getLog(UnionPayFrontRes.class);
	
    @RequestMapping(value = "/unionPayFrontRes")
    protected ModelAndView execute(HttpServletRequest request,HttpServletResponse response) {
    	logger.error("--------------- UnionPayFrontRes bankback  ---------------");
		return super.execute(request, response);
    }
    
	@Override
	protected BaseMessage buildMessage(HttpServletRequest request) {
		UnionPayMessage message = new UnionPayMessage();
	    message.setBank(BankConstants.BANK_LOGO_UNIONPAY);
		message.setRespCode(request.getParameter("respCode"));
		message.setCupReserved(request.getParameter("cupReserved"));
		message.setExchangeRate(request.getParameter("exchangeRate"));
		message.setQid(request.getParameter("qid"));
		message.setMerId(request.getParameter("merId"));
		message.setCharset(request.getParameter("charset"));
		message.setSettleDate(request.getParameter("settleDate"));
		message.setOrderCurrency(request.getParameter("orderCurrency"));
		message.setVersion(request.getParameter("version"));
		message.setSettleCurrency(request.getParameter("settleCurrency"));
		message.setSignMethod("MD5");
		message.setUpTransType(request.getParameter("transType"));
		message.setTraceNumber(request.getParameter("traceNumber"));
		message.setSettleAmount(request.getParameter("settleAmount"));
		message.setAmount(new BigDecimal(request.getParameter("orderAmount")));
		message.setMerAbbr(request.getParameter("merAbbr"));
		message.setOrderId(request.getParameter("orderNumber"));
		message.setBankOrderId(request.getParameter("orderNumber"));
		message.setTraceTime(request.getParameter("traceTime"));
		message.setRespMsg(request.getParameter("respMsg"));
		message.setRespTime(request.getParameter("respTime"));
		message.setSignMessage(request.getParameter("signature"));
		message.setExchangeDate(request.getParameter("exchangeDate"));
		message.setFront(true);
        //银行业务产品00个人网银支付
        message.setBankBusProd(BisBankBusinessProd._00);
		return message;
	}

	@Override
	protected OrderInfo buildOrderInfo(HttpServletRequest request, Result result) {
		String retCode = request.getParameter("respCode");
		UnionPayMessage message = (UnionPayMessage)result.getModel("message");
        OrderInfo orderInfo = new OrderInfo();
        String amount = request.getParameter("orderAmount");
        if(StringUtils.isNotBlank(amount)){
            amount = MoneyUtil.formatAmt(amount);
         }
        if(message!=null){
	        if(retCode!=null && retCode.equals("00")){
	            orderInfo.setOrderId(message.getOrderId());
	            orderInfo.setAmt(amount);
	            orderInfo.setNotifyNum("1");
	            orderInfo.setPayStatus("00");
	            orderInfo.setRetCode("00");
	            orderInfo.setRetMsg(request.getParameter("respMsg"));
	        }else{
	            orderInfo.setOrderId(message.getOrderId());
	            orderInfo.setAmt(amount);
	            orderInfo.setNotifyNum("1");
	            orderInfo.setPayStatus("01");
	            orderInfo.setRetCode("01");
	            orderInfo.setRetMsg("");
	        }
        }
        orderInfo.setCardType(getCardType(request));// 信用卡类型
        orderInfo.setBankName("unionpay");
        request.setAttribute("unionPay-cardType", getCardType(request));
        return orderInfo;
	}
	/**
     * 获得银行支付卡类型（cardType=01&payMode=CSPay）
     * 
     * @param request
     * @return
     */
    private String getCardType(HttpServletRequest request) {
        String str = request.getParameter("cupReserved");
        if (StringUtils.isBlank(str))
            return "error";
        String[] strs = str.replace("{", "").replace("}", "").split("&");
        if (strs == null || strs.length < 1) {
            logger.error("银行回应报文有误，不能正确解析cupReserved字段");
            return "error";
        }
        for (String cardType : strs) {
            if (cardType.startsWith("cardType")) {
                return cardType.substring(cardType.length() - 2, cardType.length());
            }
        }
        return "error";
    }

	@Override
	protected boolean checkParameters(HttpServletRequest request) {
		if (StringUtils.isEmpty(request.getParameter("qid"))
				|| StringUtils.isEmpty(request.getParameter("merId"))
				|| StringUtils.isEmpty(request.getParameter("orderAmount"))
				|| StringUtils.isEmpty(request.getParameter("orderNumber"))
				|| StringUtils.isEmpty(request.getParameter("respCode"))
				|| StringUtils.isEmpty(request.getParameter("signature"))
				|| StringUtils.isEmpty(request.getParameter("charset"))) {
		return false;
		}
		return true;
	}
}
